/*
	本程序实现的功能是对于客户端的socket套接字进行接受
	作者：杨磊
*/

#include <signal.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include <fcntl.h>
#include<sys/socket.h>
#include<netinet/in.h>

#define SIZE 1000     
#define PORT 9999
#define IP "192.168.100.2"
int service_program();

int service_program()
{
	int socketID = 0;
	int addrLength = 0;
	int ret = 0;
	int on = 1;
	struct sockaddr_in addr;
	char buf[SIZE] = {0};
	//创建套接字 
	socketID = socket(AF_INET,SOCK_STREAM,0);
	if(0 > socketID)
	{
		perror("creat socket error ");
		return -1;
	}
	printf("socket ok %d\r\n",socketID);
	
	
	//绑定地址
	addrLength = sizeof(addr);
	memset(&addr,0,addrLength);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = INADDR_ANY;
	ret = bind(socketID,(struct sockaddr*)&addr,addrLength);
	if(ret < 0)
	{
		perror("bind error");
		close(socketID);
		return -1;
	}
	printf("bind ok\r\n");
	
	//监听
	
	listen(socketID,5);
	
	//接受连接
	while(1)
	{
		int newID = accept(socketID,(struct sockaddr*)&addr,&addrLength);
		if(0 > newID)
		{
			perror("accept error!");
			close(socketID);
			return -1;
		}
		printf("client connect success,port=%d\n\r",ntohs(addr.sin_port));
	
		//通信
		
		ret  = read(newID,buf,SIZE - 1);
		if(ret > 0)
		{
			printf("server get:%s,%d\r\n",buf,ret);
		}	
		if(ret < 0)
		{
			printf("server get error!");
		}
		int fd = open("/phonenum.txt",O_WRONLY|O_TRUNC|O_CREAT,0666);
		if(fd < 0)
		{
			perror("open error!");
			
			return -1;
		}
		write(fd,buf,SIZE - 1);
		printf("write success!");
	
		/*memset(buf,0,SIZE);
		
		fgets(buf,SIZE - 1,stdin);
		ret = send(newID,buf,strlen(buf),0);
		if(ret > 0)
		{
			printf("server send ok\r\n");
		}*/
		//关闭套接字  close()
		close(newID);
		close(socketID);
	}
		return 0;
	
}
void init_daemon(void)
{

    int pid;
    int i;
    if(pid=fork())
        exit(0);        //是父进程，结束父进程
    else if(pid< 0)
        exit(1);        	//fork失败，退出
						//是第一子进程，后台继续执行
    setsid();           //第一子进程成为新的会话组长和进程组长
					//并与控制终端分离
    if(pid=fork())
 /*   {
		FILE *fp;
		int cha;
		sleep(1);
		if((fp = fopen("/test.txt","a")) >=0)
		{
			fprintf(fp,"light%d\n",pid);
            fclose(fp);
		}
		exit(0); 
	} */ 
		exit(0); 	//是第一子进程，结束第一子进程
    else if(pid< 0)

        exit(1);        //fork失败，退出

    //是第二子进程，继续

    //第二子进程不再是会话组长
    for(i=0;i< NOFILE;++i)  //关闭打开的文件描述符
        close(i);
    chdir("/tmp");      //改变工作目录到/tmp
    umask(0);           //重设文件创建掩模
    return;

}
int main()
{
	init_daemon();
	service_program();
	return 0;
	
}
